package com.anmingle.pswb.controller;

import com.anmingle.common.R;
import com.anmingle.common.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Random;

/**
 * @author 安明乐
 * @Title test
 * @Package IntelliJ IDEA
 * @date 2022/12/6 23:24
 */
@RequestMapping
@RestController
@Slf4j
public class UploadController {


    @PostMapping("/upload/picture")
    public ResponseResult<String> uploadPicture(HttpServletRequest request) throws UnsupportedEncodingException {

        String filePath = "";

        //设置编码
        request.setCharacterEncoding("utf-8");

        ApplicationHome h = new ApplicationHome(getClass());
        File p = h.getSource();
        //设置储存地址
        String path = p.getParentFile().toString()+"/user/";

        File dir = new File(path);

        log.info("服务器地址:"+path);
        //文件目录不存在，就创建一个
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值

            Iterator<String> iterator = req.getFileNames();


            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileName = getFilename();

                //Random rand = new Random();
                //int sj = rand.nextInt(50);

                //获取图片后缀
                String kzm = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));;
                //String filename = name1 +sj+ kzm;
                File file1 = new File(path+fileName+kzm);

                System.out.println(path+fileName);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file1));


                out.write(file.getBytes());
                out.close();
                //直接上路径和名字  前端拼接url
                filePath = fileName;

                //之前是每个服务器域名加端口号直接访问  如果更改服务器则无法则获取图片
                System.out.println("访问图片路径:" + request.getScheme() + "://" +
                        request.getServerName() + ":"
                        + request.getServerPort()+"/image/"+fileName);

            }
        } catch (Exception e) {
            log.info("上传图片错误:" +e);
        }
        return R.ok(filePath);
    }

    /***
     *随机生成10位数的图片名称
     * @return
     */
    private static String getFilename() {
        String d = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
        String t = "";
        Random random = new Random();
        char[] chars = d.toCharArray();
        for (int i = 0; i < 10; i++) {
            t += chars[random.nextInt(d.length())];

        }
        return t;
    }

}
